﻿using SuperX.Common;
using SuperX.Common.Collection;
using SuperX.DataService;
using SuperX.Helper.ServiceResponse;
using SuperX.DeviceService.Ledger;
using SuperX.DeviceService.Model;
using SuperX.DeviceService.Template;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;

namespace SuperX.DeviceService
{
    public class DeviceConfig : BasicObjCollection<DriverConfig>
    {
        public int DELAY { get; set; } = 3000;
        public int MAXHDACAP { get; set; } = 10000;
        public int ALARMLIMIT { get; set; } = 1000;
        public int CYCLE { get; set; } = 30000;
        public int CYCLE2 { get; set; } = 600000;
        public int SENDTIMEOUT { get; set; } = 60000;
        public int HDALEN { get; set; } = 1024 * 1024;
        public int MAXLOGSIZE { get; set; } = 1024;
        public int HDADELAY { get; set; } = 3600 * 1000;
        public int ALARMDELAY { get; set; } = 3600 * 1000;
        public int ARCHIVEINTERVAL { get; set; } = 100;

        [JsonIgnore]
        public string PublicKey { get => "<RSAKeyValue><Modulus>wNK/GAtv/OueVqZ4KLNoPez8l2KJScMpbBFxNpatyXkupKhgUTrOaDdzDRSfU/9t1pmGQfjFQ5ukFo6W+41yuFrWqXPdWFF62tYUsVA4hOnbyA/VsShxUBYmAYdDDI/wq2ygByhCVWAiqfXiisLJKb0sB803SUaln4eWt9mCOiU=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>"; }

        [JsonIgnore]
        public string LicenseFilePath { get => Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "IOT.key"); }

        private ListObjectCollection<DeviceConfig, DriverConfig> _configGroup;

        public ListObjectCollection<DeviceConfig, DriverConfig> DriverGroups
        {
            get => _configGroup ?? (_configGroup = new ListObjectCollection<DeviceConfig, DriverConfig>(this));
            set
            {
                _configGroup = value;
                _configGroup.SetParent(this);
            }
        }

        /// <summary>
        /// 模板配置文件
        /// </summary>
        private TemplateConfig _templateConfig;

        public TemplateConfig TemplateConfig
        {
            get => _templateConfig ?? (_templateConfig = new TemplateConfig());
            set => _templateConfig = value;
        }

        /// <summary>
        /// 默认驱动的根目录配置文件名称
        /// </summary>
        public string DefaultDriverCfgName { get; set; } = "DefaultDriverConfig.cfg";

        /// <summary>
        /// 默认驱动配置
        /// </summary>
        [JsonIgnore]
        public List<DriverConfig> DefaultDriverConfig
        {
            get => _defaultDriverConfig ?? (_defaultDriverConfig = new List<DriverConfig>());
            set => _defaultDriverConfig = value;
        }

        public DeviceConfig()
        {
            this.Name = "Tag";
        }

        /// <summary>
        /// 设备节点名
        /// </summary>
        public Dictionary<string, TreeModel> DeviceNodeNames
        {
            get => _deviceNodeNames ?? (_deviceNodeNames = new Dictionary<string, TreeModel>());
            set
            {
                _deviceNodeNames = value;
            }
        }

        private Dictionary<string, TreeModel> _deviceNodeNames;

        private Dictionary<string, EquipmentLedger> _EquipmentLedgers = new Dictionary<string, EquipmentLedger>();

        public Dictionary<string, EquipmentLedger> EquipmentLedgers
        {
            get => _EquipmentLedgers;
            set
            {
                if (value != _EquipmentLedgers)
                {
                    _EquipmentLedgers = value;
                }
            }
        }

        public override DriverConfig this[string name] => DriverGroups.Values.FirstOrDefault(a => a.Name == name);

        public override List<string> GetKeys()
        {
            return DriverGroups.Values.Select(a => a.Name).ToList();
        }

        public override List<DriverConfig> GetValues()
        {
            return DriverGroups.Values;
        }

        public override bool IsUniqueName(string name, IObjCollection parent)
        {
            if (parent != null)
            {
                return parent.IsUniqueName(name, null);
            }

            return true;
        }

        #region 设备命名

        /// <summary>
        /// 根据设备类型获取新的设备名字
        /// </summary>
        /// <param name="strDeviceType"></param>
        /// <returns></returns>
        public string GetNewDeviceName(string strDeviceType)
        {
            string name = "";
            if (!string.IsNullOrEmpty(strDeviceType) && !string.IsNullOrWhiteSpace(strDeviceType))
            {
                strDeviceType = strDeviceType.Replace("-", "");//"-"为非法字符，所以在这里把它替换为空
                strDeviceType = strDeviceType.Replace("/", "");//"/"为非法字符，所以在这里把它替换为空
                strDeviceType = strDeviceType.Replace(" ", "");//" "为非法字符，所以在这里把它替换为空
                name = GetNewDeviceName(strDeviceType, 1);
            }
            else
            {
                name = GetNewDeviceName("Device", 1);
            }
            return name;
        }

        /// <summary>
        /// 获取新的设备名字
        /// </summary>
        /// <param name="name"></param>
        /// <param name="deviceNo"></param>
        /// <returns></returns>
        public string GetNewDeviceName(string name, int deviceNo)
        {
            string deviceName = "";
            if (name.Trim() == "")
            {
                name = "Device";
            }
            try
            {
                deviceName = name + deviceNo.ToString().Trim();
                if (JudgeExistDevice(DriverGroups, deviceName))
                {
                    deviceName = GetNewDeviceName(name, deviceNo + 1);
                }
            }
            catch (Exception)
            {
                throw;
            }
            return deviceName;
        }

        /// <summary>
        /// 判断传进来的device名字是否已经在集合中存在
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool JudgeExistDevice(ListObjectCollection<DeviceConfig, DriverConfig> deviceCollections, string name)
        {
            if (name != null)
            {
                foreach (var item in deviceCollections.Values)
                {
                    var deviceViewModel = item as DriverConfig;
                    if (item.Name == name)
                    {
                        return true;
                    }
                }

                if (JudgeExistGroupName(name))
                {
                    return true;
                }
                return false;
            }
            else
            {
                return true;
            }
        }

        public bool JudgeExistGroupName(string name)
        {
            bool exist = false;
            if (DeviceNodeNames.Count > 0)
            {
                foreach (var item in DeviceNodeNames.Values)
                {
                    if (item.Name == name)
                    {
                        exist = true; break;
                    }
                }
            }
            return exist;
        }

        #endregion 设备命名

        private List<DriverConfig> _defaultDriverConfig;
    }
}